/* eslint-disable vue/one-component-per-file */
import XLSX from 'xlsx';
import { readFileSync } from 'fs-extra';
import path, { basename, dirname, join } from 'path';
import { createApp, App, defineComponent } from 'vue';
const panelDataMap = new WeakMap<any, App>();
/**
 * @zh 如果希望兼容 3.3 之前的版本可以使用下方的代码
 * @en You can add the code below if you want compatibility with versions prior to 3.3
 */
// Editor.Panel.define = Editor.Panel.define || function(options: any) { return options }
module.exports = Editor.Panel.define({
    listeners: {
        show() { console.log('show'); },
        hide() { console.log('hide'); },
    },
    template: readFileSync(join(__dirname, '../../../static/template/default/index.html'), 'utf-8'),
    style: readFileSync(join(__dirname, '../../../static/style/default/index.css'), 'utf-8'),
    $: {
        app: '#app',
        text: '#text',
    },
    methods: {
        hello() {
            if (this.$.text) {
                this.$.text.innerHTML = 'hello';
                console.log('[cocos-panel-html.default]: hello');
            }
        },
    },
    ready() {
        if (this.$.text) {
            this.$.text.innerHTML = '---Excel转Json工具---';
        }
        if (this.$.app) {
            const app = createApp({});
            app.config.compilerOptions.isCustomElement = (tag) => tag.startsWith('ui-');

            app.component('MyCounter', defineComponent({
                data() {
                    return {
                        excelFilePath: '',
                        jsonOutputPath: 'db://assets/', // 默认输出路径
                        skipRows: 0, // 跳过的行数
                        useHeader: true,// 是否使用第一行作为表头
                        previewData: '', //预览数据
                        jsonFileName: 'data.json', //文件名
                        result: {}
                    }
                },
                methods: {
                    async selectExcelFile() {
                        const config: any = {};
                        config.filters = [
                            { name: 'Excel Files', extensions: ['xlsx', 'xls'] },
                        ];
                        const data = await Editor.Dialog.select(config);
                        this.excelFilePath = data.filePaths[0];
                        console.log(data);
                        //预览
                        this.previewJsonData();
                    },
                    /*添加预览功能*/
                    async previewJsonData() {
                        const workbook = XLSX.readFile(this.excelFilePath);
                        const result: { [key: string]: any } = {};
                        workbook.SheetNames.forEach(sheetName => {
                            const worksheet = workbook.Sheets[sheetName];
                            result[sheetName] = XLSX.utils.sheet_to_json(worksheet, {
                                range: this.skipRows > 0 ? this.skipRows : 0,
                                header: this.useHeader ? 0 : 1,
                                rawNumbers: true
                            });
                        });
                        this.result = result;
                        this.previewData = JSON.stringify(result, null, 2).slice(0, 1000) + '...';
                    },
                    async selectOutputFile() {
                        const defaultPath = join(Editor.Project.path, 'assets', this.jsonFileName);

                        const result = await Editor.Dialog.save({
                            title: '保存JSON文件',
                            path: defaultPath,  // 设置默认路径
                            filters: [{
                                name: 'JSON Files',
                                extensions: ['json']
                            }],
                        });

                        if (!result.canceled && result.filePath) {
                            // 转换为相对路径（相对于项目目录）
                            this.jsonOutputPath = dirname(result.filePath);
                            this.jsonFileName = basename(result.filePath);
                        }
                        // 如果取消则保持原有路径不变
                    },
                    async convertToJson() {
                        try {
                            // 确定最终保存路径
                            let savePath: string;

                            if (this.jsonOutputPath.startsWith('db://')) {
                                savePath = join(Editor.Project.path, this.jsonOutputPath.replace('db://', ''), this.jsonFileName);
                            } else {
                                savePath = join(this.jsonOutputPath, this.jsonFileName);
                            }

                            // 确保目录存在
                            const fs = require('fs-extra');
                            await fs.ensureDir(dirname(savePath));

                            // 保存文件
                            await fs.writeJson(savePath, this.result, { spaces: 2 });

                            const relativePath = path.relative(Editor.Project.path, savePath);
                            const dbPath = `db://${relativePath.replace(/\\/g, '/')}`;
                            // 刷新资源管理器
                            await Editor.Message.request('asset-db', 'refresh-asset', dbPath);

                            console.log(`转换成功！保存路径：${dbPath}`);
                        } catch (error) {
                            console.error('转换失败：', error);
                        }
                    },
                    onConfirm(event: any) {
                        // skipRows通过v-model.number已经自动更新
                        console.log("skipRows : ", this.skipRows);
                        this.previewJsonData();
                    },
                    handleHeaderConfirm(event: any) {
                        this.useHeader = event.target.value === true;
                        console.log("useHeader : ", this.useHeader);
                        this.previewJsonData();
                    },
                },
                template: readFileSync(join(__dirname, '../../../static/template/vue/Conversion.html'), 'utf-8'),
            }));
            app.mount(this.$.app);
            panelDataMap.set(this, app);
        }
    },
    beforeClose() { },
    close() {
        const app = panelDataMap.get(this);
        if (app) {
            app.unmount();
        }
    },
});
